<template>
  <el-dialog
    :append-to-body="true"
    :visible.sync="dialog"
    :title="is_create?'添加设备':'编辑设备'"
    width="620px"
  >
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="设备名称" prop="name">
        <el-input placeholder="请输入设备名称" v-model="form.name" maxlength="20" />
      </el-form-item>
      <el-form-item label="详细地址" prop="gatewayAddress">
        <el-input placeholder="请输入详细地址" v-model="form.gatewayAddress" />
      </el-form-item>
      <el-form-item label="设备型号" prop="modelNo">
        <el-input placeholder="请输入设备型号" v-model="form.modelNo" :disabled="!is_create" />
      </el-form-item>
      <el-form-item label="设备KEY" prop="keyname">
        <el-input placeholder="请输入设备KEY" v-model="form.keyname" :disabled="!is_create" />
      </el-form-item>
      <el-form-item label="设备地址" prop="adr">
        <el-input placeholder="请输入设备地址" v-model="form.adr" :disabled="!is_create" />
      </el-form-item>
      <el-form-item label="设备IMEI" prop="imei">
        <el-input placeholder="请输入设备IMEI号" v-model="form.imei" :disabled="!is_create" />
      </el-form-item>
      <el-form-item label="相位类型" prop="phaseType" style="width:264px;">
        <el-select v-model="form.phaseType" placeholder="请选择" style="width:184px;">
          <el-option
            v-for="item in [{name:'单相',id:'1'},{name:'三相',id:'3'}]"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属行业" prop="cid" style="width:264px;">
        <el-select v-model="form.cid" placeholder="选择所属行业" style="width:184px;">
          <el-option
            v-for="item in industry_list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属网关" prop="gatewayId" style="width:264px;">
        <el-select v-model="form.gatewayId" placeholder="选择所属网关" style="width:184px;">
          <el-option
            v-for="item in gateways_list"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态">
        <el-radio-group v-model="form.status" disabled>
          <el-radio label="1">正常</el-radio>
          <el-radio label="0">离线</el-radio>
          <el-radio label="2">报警</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属区域">
        <el-input v-model="area" disabled />
        <!-- <em v-text="area" style="cursor: not-allowed;"></em> -->
      </el-form-item>
      <em v-if="!is_create">
        <div class="mb20 fz16 bold">预设参数</div>
        <el-form-item label="电流" style="width:264px;">
          <el-input placeholder="线缆电流" v-model="form.a" style="width:160px;" />
          <em>A</em>
        </el-form-item>
        <el-form-item label="剩余电流" style="width:264px;">
          <el-input placeholder="剩余电流" v-model="form.listA" style="width:145px;" />
          <em>mA</em>
        </el-form-item>
        <el-form-item label="温度" style="width:264px;">
          <el-input placeholder="线缆温度" v-model="form.t" style="width:160px;" />
          <em>℃</em>
        </el-form-item>
        <el-form-item label="电压" style="width:264px;">
          <el-input placeholder="线缆电压" v-model="form.u" style="width:145px;" />
          <em>V</em>
        </el-form-item>
      </em>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loading" size="medium" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  _industryAllGet,
  _gatewaysAllGet,
  _equipmentCreate,
  _equipmentUpdate,
  _findImei,
  _location
} from "@/http/ajax";
export default {
  props: {
    sup_this: {
      type: Object,
      default: null
    },
    gat_id: {
      type: Number,
      default: 0
    },
    is_create: {
      type: Boolean,
      required: true
    }
  },
  name: "create",
  data() {
    const validmodelNo = (rule, value, callback) => {
      if (!value) {
        callback(new Error("设备型号不能为空"));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error("设备型号格式错误"));
      } else {
        callback();
      }
    };
    const validKeyname = (rule, value, callback) => {
      if (!value) {
        callback(new Error("设备KEY不能为空"));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error("设备KEY格式错误"));
      } else {
        callback();
      }
    };
    const validimei = (rule, value, callback) => {
      if (!value) {
        callback(new Error("设备IMEI不能为空"));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error("设备IMEI格式错误"));
      } else {
        callback();
      }
    };
    const validadr = (rule, value, callback) => {
      if (!value) {
        callback(new Error("设备地址不能为空"));
      } else if (!this.isvalidPhone(value)) {
        callback(new Error("设备地址格式错误"));
      } else {
        callback();
      }
    };

    return {
      dialog: false,
      loading: false,
      form: {
        status: "0",
        name: "",
        modelNo: "",
        keyname: "",
        gatewayAddress: "",
        phaseType: 1,
        gatewayId: "",
        cid: "",
        imei: "",
        adr: ""
      },
      area: "-",
      rules: {
        name: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        gatewayAddress: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        modelNo: [{ required: true, validator: validmodelNo, trigger: "blur" }],
        keyname: [{ required: true, validator: validKeyname, trigger: "blur" }],
        imei: [{ required: true, validator: validimei, trigger: "blur" }],
        adr: [{ required: true, validator: validadr, trigger: "blur" }],
        gatewayId: [
          { required: true, message: "请选择网关", trigger: "change" }
        ],
        phaseType: [
          { required: true, message: "请选择相位类型", trigger: "change" }
        ],
        cid: [{ required: true, message: "请选择行业", trigger: "change" }]
      },
      industry_list: [], // 行业分类
      gateways_list: [] // 网关分类
    };
  },
  watch: {
    "form.gatewayId": function(val) {
      this.area = this.getArea();
    }
  },
  methods: {
    getArea() {
      let addrs = "";
      this.gateways_list.forEach(el => {
        if (el.id === this.form.gatewayId) {
          addrs = el.province.name + el.city.name + el.district.name;
        }
      });
      return addrs;
    },
    domInit(edit) {
      this.$refs["form"].resetFields();
      this.getIndustry();
      this.getGateways(edit);
    },
    getLocation() {
      let address = this.getArea() + this.form.gatewayAddress;
      _location(
        { address: address },
        res => {
          let data = this.form;
          data["lng"] = res.lng;
          data["lat"] = res.lat;
          if (this.is_create) {
            this.form["imeiTablename"] = this.form.imei + "_" + this.form.adr;
            this.findImei(data);
          } else {
            data.u = +data.u * 10;
            data.a = +data.a * 10;
            this.upDataEquipment(data);
          }
        },
        err => {
          console.log(err);
        }
      );
    },
    doSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          let mdzz = true;
          this.gateways_list.forEach(el => {
            if (el.id === this.form.gatewayId) {
              if (this.form.imei != el.proKey) {
                mdzz = false;
              }
            }
          });
          if (!mdzz && this.is_create) {
            this.loading = false;
            this.$message({
              message: "IMEI无法匹配。",
              type: "error"
            });
          } else {
            this.getLocation();
          }
        }
      });
    },
    // 修改
    upDataEquipment(data) {
      _equipmentUpdate(
        data,
        res => {
          this.dialog = false;
          this.sup_this.getList();
          this.$refs["form"].resetFields();
        },
        err => {}
      );
    },
    // 检测 iemi
    findImei(data) {
      _findImei(
        { imei: data.imei, adr: data.adr },
        res => {
          if (res.status === 200) {
            //   提交
            _equipmentCreate(
              data,
              res => {
                this.dialog = false;
                this.sup_this.getList();
                this.$refs["form"].resetFields();
              },
              err => {}
            );
          } else {
            this.loading = false;
            this.$message({
              message: "该设备已添加，请检查输入",
              type: "error"
            });
          }
        },
        err => {
          this.loading = false;
        }
      );
    },
    // 获取设备分类
    getIndustry() {
      _industryAllGet(
        res => {
          this.industry_list = res;
        },
        err => {}
      );
    },
    // 获取网关类型
    getGateways(edit) {
      let user = JSON.parse(sessionStorage.user);
      let data = {
        deptId: user.deptId || user.dept.id || "",
        level: sessionStorage.level
      };
      _gatewaysAllGet(
        data,
        res => {
          this.gateways_list = res;
          if (edit) {
            this.area = this.getArea();
          }
        },
        err => {}
      );
    },
    isvalidPhone(str) {
      const reg = /^[0-9a-zA-Z]*$/g;
      return reg.test(str);
    }
  }
};
</script>

<style lang="scss">
.el-radio__input.is-disabled.is-checked .el-radio__inner::after {
  background-color: #fff;
}
.el-radio__input.is-disabled.is-checked .el-radio__inner {
  background-color: #338ff6;
  border-color: #338ff6;
}
.el-radio__input.is-disabled.is-checked + span.el-radio__label {
  color: #338ff6;
}
.el-radio {
  margin-right: 10px;
}
</style>
